package org.qiyu.live.im.router.provider.service.impl;

import jakarta.annotation.Resource;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.rpc.RpcContext;
import org.qiyu.live.im.core.server.interfaces.constants.ImCoreServerConstants;
import org.qiyu.live.im.core.server.interfaces.rpc.IRouterHandlerRpc;
import org.qiyu.live.im.dto.ImMsgBody;
import org.qiyu.live.im.router.provider.service.ImRouterServer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: //todo
 * @Author: 张广焱
 * @Date: 2024-05-04 上午10:46
 */
@Service
public class ImRouterServiceImpl implements ImRouterServer {

    @DubboReference
    private IRouterHandlerRpc routerHandlerRpc;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean sendMsg(ImMsgBody imMsgBody) {
        String bindAddress = stringRedisTemplate.opsForValue().get(ImCoreServerConstants.IM_BIND_IP_KEY + imMsgBody.getAppId() + ":" + imMsgBody.getUserId());
        if (StringUtils.isEmpty(bindAddress)) {
            return false;
        }
        bindAddress = bindAddress.substring(bindAddress.indexOf("%"));
        RpcContext.getContext().set("ip", bindAddress);
        routerHandlerRpc.sendMsg(imMsgBody);
        return true;
    }

    @Override
    public void batchSendMsg(List<ImMsgBody> imMsgBodies) {
        List<Long> userIdList = imMsgBodies.stream().map(ImMsgBody::getUserId).collect(Collectors.toList());
        Map<Long, ImMsgBody> userIdMsgMap = imMsgBodies.stream().collect(Collectors.toMap(ImMsgBody::getUserId, imMsgBody -> imMsgBody));
        //保证整个list集合集合的appid是同一个
        int appId = imMsgBodies.get(0).getAppId();
        List<String> cacheKeyList = new ArrayList<>();
        userIdList.forEach(userId -> {
            cacheKeyList.add(ImCoreServerConstants.IM_BIND_IP_KEY + appId + ":" + userId);
        });
        //批量取出每个用户绑定的ip地址
        List<String> ipList = stringRedisTemplate.opsForValue().multiGet(cacheKeyList).stream().filter(x -> x != null).collect(Collectors.toList());
        Map<String, List<Long>> userIdMap = new HashMap<>();
//        ipList.forEach(ip -> {
//            String currentIp = ip.substring(ip.indexOf("%"));
//            Long userId = Long.valueOf(ip.substring(ip.indexOf("%"), -1));
//            List<Long> currentUserIdList = userIdMap.get(currentIp);
//            if (currentUserIdList == null) {
//                currentUserIdList = new ArrayList<>();
//            }
//            currentUserIdList.add(userId);
//            userIdMap.put(currentIp, currentUserIdList);
//        });
        //批量取出每个用户的id地址
        ipList.forEach(ip -> {
            String currentIp = ip.substring(ip.indexOf("%") + 1);
            Long userId = Long.valueOf(ip.substring(0, ip.indexOf("%")));
            userIdMap.computeIfAbsent(currentIp, k -> new ArrayList<>()).add(userId);
        });
        //将连接同一台ip地址的imMsgBody组装到一个list中，然后进行统一的发送
        for (String currentIp : userIdMap.keySet()) {
            // 记录当前ip的userId列表 临时存储
            RpcContext.getContext().set("ip", currentIp);
            List<ImMsgBody> objects = new ArrayList<>();
            List<Long> ipBindUserIdList = userIdMap.get(currentIp);
            ipBindUserIdList.forEach(userid -> {
                ImMsgBody imMsgBody = userIdMsgMap.get(userid);
                objects.add(imMsgBody);
            });
            routerHandlerRpc.batchSendMsg(objects);
        }
    }
}
